using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Summary description for AcmsConfigManager
/// </summary>
public class AcmsConfigManager
{

    private AcmsConfigManager()
    {
    }

    private static string configFilePath = HttpContext.Current.Server.MapPath("~/web.config");

    /// Returns the Web.config as XmlDocument
    private static XmlDocument GetWebConfig()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(configFilePath);
        return xmlDoc;
    }

    /// Checks for the appSettings node in Web.config
    /// Updates the value for the given key if the key
    /// already exists or creates a new node for the
    /// given key and value combination if it is not present
    public static void SetAppSetting( string key, string val )
    {
        XmlDocument xmlDoc = GetWebConfig();
        XmlNode xmlNode = xmlDoc.SelectSingleNode("//appSettings");

        if( xmlNode == null )
        {
            throw new Exception("appSettings node not found!");
        }
        
        string nodeFormat = string.Format("//add[@key='{0}']", key);
        XmlElement xmlElement =(XmlElement) xmlNode.SelectSingleNode( nodeFormat );
        if( xmlElement != null )
        {
            xmlElement.SetAttribute( "value", val );
        }
        else
        {
            xmlElement = xmlDoc.CreateElement( "add" );
            xmlElement.SetAttribute( "key", key );
            xmlElement.SetAttribute( "value", val );
            xmlNode.AppendChild( xmlElement );
        }
        SaveWebConfig( xmlDoc );
    }

    /// Saves the changes to the Web.config file
    private static void SaveWebConfig( XmlDocument xmlDoc )
    {
        XmlTextWriter writer = null;
        try
        {
            writer = new XmlTextWriter( configFilePath, null );
            writer.Formatting = Formatting.Indented;
            xmlDoc.WriteTo( writer );
            writer.Flush();
        }
        finally
        {
            if (writer != null && writer.WriteState != WriteState.Closed)
            {
                writer.Close();
            }
        }
    }
}
